package com.ocm.tourism.core.dao.jpa;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.ocm.tourism.core.dao.GenericDao;

public class JpaGenericDao<T extends Object> implements GenericDao<T> {

   private Class<T> clazz;

   public void setClazz( final Class< T > clazzToSet ){
      this.clazz = clazzToSet;
   }

   @PersistenceContext
   transient EntityManager entityManager;

   public final EntityManager entityManager() {
      EntityManager em = entityManager;
      if (em == null)
         throw new IllegalStateException(
               "Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
      return em;
   }

   public T find(Long id) {
      if (id == null)
         return null; 
      return entityManager().find(clazz, id);
   }

   public void save(T t) {
      if (this.entityManager == null)
         this.entityManager = entityManager();
      this.entityManager.persist(t);
   }

   public void remove(long id) {
      if (this.entityManager == null)
         this.entityManager = entityManager();
      T attached = this.find(id);
      if (this.entityManager.contains(attached)) {
         this.entityManager.remove(attached);
      } 
   }

   public void flush() {
      if (this.entityManager == null)
         this.entityManager = entityManager();
      this.entityManager.flush();
   }

   public void clear() {
      if (this.entityManager == null)
         this.entityManager = entityManager();
      this.entityManager.clear();
   }

   public T merge(T t) {
      if (this.entityManager == null)
         this.entityManager = entityManager();
      T merged = this.entityManager.merge(t);
      return merged;
   }

   public T update(T t) {
      T merged = merge(t);
      return  merged;
   }
}
